//
//  MarketViewController.swift
//  Nahuo
//
//  Created by zang qilong on 2017/5/12.
//  Copyright © 2017年 zang qilong. All rights reserved.
//

import UIKit
import URLNavigator
import SnapKit
import SwiftyJSON

final class MarketViewController: UIViewController {
    
    
    var sliderCollectionView: UICollectionView!
    let fetchTypeRequest = FetchAllMarketTypeRequest()
    var marketArray = [MarketType]()
    let newProductChildView = MarketNewProductTableViewController(style: .plain, type: "1")
    var typeProductChildView:MarketTypeCollectionViewController!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupViews()
        fetchType()
        setupTypeChildView()
        setupNewProductChildView()
        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    // MARK: Common Init
    
    func setupViews() {
        self.title = "逛市场"
        self.view.backgroundColor = UIColor.tableBGColor()
        self.automaticallyAdjustsScrollViewInsets = false
        self.navigationController?.navigationBar.shadowImage = UIImage()
        self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
        
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal
        sliderCollectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
        sliderCollectionView.backgroundColor = UIColor.white
        sliderCollectionView.dataSource = self
        sliderCollectionView.delegate = self
        sliderCollectionView.register(UINib.init(nibName: SliderCollectionViewCell.reuseID(), bundle: nil), forCellWithReuseIdentifier: SliderCollectionViewCell.reuseID())
        self.view.addSubview(sliderCollectionView)
        sliderCollectionView.snp.makeConstraints { (maker) in
            maker.top.equalTo(self.view)
            maker.left.equalTo(self.view)
            maker.right.equalTo(self.view)
            maker.height.equalTo(44)
        }

        let leftButton = UIButton.init(type: .custom)
        leftButton.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
        leftButton.setImage(UIImage.init(named: "home_search_black"), for: .normal)
        let leftBarButton = UIBarButtonItem.init(customView: leftButton)
        let negativeSpacerLeft = UIBarButtonItem.init(barButtonSystemItem: UIBarButtonSystemItem.fixedSpace, target: nil, action: nil)
        negativeSpacerLeft.width = -20
        self.navigationItem.leftBarButtonItems = [negativeSpacerLeft, leftBarButton]
        
        let rightButton = UIButton.init(type: .custom)
        rightButton.setImage(UIImage.init(named: "my_message_black"), for: .normal)
        rightButton.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
        let rightBarButton = UIBarButtonItem.init(customView: rightButton)
        let negativeSpacerRight = UIBarButtonItem.init(barButtonSystemItem: UIBarButtonSystemItem.fixedSpace, target: nil, action: nil)
        negativeSpacerRight.width = -20
        self.navigationItem.rightBarButtonItems = [negativeSpacerRight, rightBarButton]
    }
    
    // MARK: - Request
    
    func fetchType() {
        fetchTypeRequest.startWithCompletionBlock(success: { [unowned self](request) in
            let json = JSON(request.responseObject as Any)
            if let code = json["code"].int, code == 0 {
                if let data = json["data"].arrayObject {
                    self.marketArray.removeAll()
                    for object in data {
                        print("\(object)");
                        if let model = MarketType.yy_model(withJSON: object){
                            self.marketArray.append(model)
                            print("\(model.name), \(model.type)")
                        }
                        
                    }
                    self.sliderCollectionView.reloadData()
                    self.sliderCollectionView.selectItem(at: IndexPath(item: 0, section: 0), animated: true, scrollPosition: .top)
                }
            }
        }) { (request) in
            
        }
    }
    
    func setupNewProductChildView() {
        self.addChildViewController(newProductChildView)
        self.view.addSubview(newProductChildView.view)
        newProductChildView.view.snp.makeConstraints { (make) in
            make.top.equalTo(self.sliderCollectionView.snp.bottom).offset(10)
            make.left.equalTo(self.view)
            make.right.equalTo(self.view)
            make.bottom.equalTo(self.view.snp.bottom);
        }
        newProductChildView.didMove(toParentViewController: self)
    }
    
    func setupTypeChildView() {
        let layout = UICollectionViewFlowLayout()
        typeProductChildView = MarketTypeCollectionViewController(collectionViewLayout: layout)
        self.addChildViewController(typeProductChildView)
        self.view.addSubview(typeProductChildView.view)
        typeProductChildView.view.snp.makeConstraints { (make) in
            make.top.equalTo(self.sliderCollectionView.snp.bottom).offset(10)
            make.left.equalTo(self.view)
            make.right.equalTo(self.view)
            make.bottom.equalTo(self.view.snp.bottom);
        }
        typeProductChildView.didMove(toParentViewController: self)
    }
    
}

extension MarketViewController:URLNavigable {
    convenience init?(navigation: Navigation) {
        self.init(nibName: nil, bundle: nil)
    }

}

extension MarketViewController:UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: SliderCollectionViewCell.reuseID(), for: indexPath) as! SliderCollectionViewCell
        let model = marketArray[indexPath.row]
        cell.categoryLabel.text = model.name
        return cell
        
    }
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return marketArray.count
    }
    
}

extension MarketViewController: UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if indexPath.row == 0 {
            self.view.bringSubview(toFront: newProductChildView.view)
        }else {
            let market = marketArray[indexPath.row]
            self.view.bringSubview(toFront: typeProductChildView.view)
            typeProductChildView.fetchProcut(type: market.type, isRefresh: true)
        }
    }
}

extension MarketViewController: UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let model = marketArray[indexPath.row]
        let title = model.name as NSString
        let size = title.size(attributes: [NSFontAttributeName: UIFont.pingfangRegularFont(size: 15)])
        return CGSize(width: size.width + 30, height: 25)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsetsMake(0, 10, 0, 0)
    }
}
